package com.limh.base.service

import com.limh.base.comm.Comm.BASE_URL
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException

/**
 * @function：极客数据
 * @author： limh
 * @date： 2018/9/24
 * Copyright @2018 Corpration Name
 */
class Geek private constructor() {

    private var retrofit: Retrofit

    init {
        val httpClient = OkHttpClient.Builder()
        val builder = Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(BASE_URL)
        retrofit = builder.client(httpClient.addNetworkInterceptor(HttpInterceptor()).build()).build()
    }

    fun createApi(): Api {
        return retrofit.create(Api::class.java)
    }

    internal inner class HttpInterceptor : Interceptor {

        @Throws(IOException::class)
        override fun intercept(chain: Interceptor.Chain): Response {
            val builder = chain.request().newBuilder()
            val requst = builder
                    .addHeader("Content-Type", "application/json; charset=utf-8")
                    .build()
            return chain.proceed(requst)
        }
    }

    companion object {
        fun getInstance() = Helper.instance
    }

    private object Helper {
        val instance = Geek()
    }
}